package com.googlecode.httpclientgae

import java.net.InetAddress
import java.net.Socket
import java.util.concurrent.TimeUnit

import org.apache.http.conn.routing.HttpRoute
import org.apache.http.conn.scheme.Scheme
import org.apache.http.conn.scheme.SchemeRegistry
import org.apache.http.conn.scheme.SocketFactory
import org.apache.http.impl.client.DefaultHttpClient
import org.apache.http.params.{BasicHttpParams, HttpParams}
import org.apache.http.conn.{ClientConnectionManager, ClientConnectionRequest, ManagedClientConnection}

class GaeHttpClient extends DefaultHttpClient(new GaeConnectionManager, new BasicHttpParams)

class GaeConnectionManager extends ClientConnectionManager {

  private val schemeRegistry: SchemeRegistry = new SchemeRegistry

  {
    val noSocketFactory = new SocketFactory() {
      def connectSocket(sock: Socket, host: String, port: Int,
                        localAddress: InetAddress, localPort: Int,
                        params: HttpParams) = null

      def createSocket = null

      def isSecure(socket: java.net.Socket) = false
    }
    schemeRegistry.register(new Scheme("http", noSocketFactory, 80))
    schemeRegistry.register(new Scheme("https", noSocketFactory, 443))
  }

  def getSchemeRegistry = schemeRegistry

  def requestConnection(route: HttpRoute, state: Object) = new ClientConnectionRequest {
    def abortRequest = {}

    def getConnection(timeout: Long = 0, tunit: TimeUnit = TimeUnit.MILLISECONDS) =
      new GaeClientConnection(GaeConnectionManager.this, route, state)
  }

  def shutdown = {}

  def closeExpiredConnections = {}

  def closeIdleConnections(idletime: Long, tunit: TimeUnit) = {}

  def releaseConnection(conn: ManagedClientConnection, validDuration: Long, timeUnit: TimeUnit) = {}

}